package siga.modelo;

import java.io.*;
import java.util.TreeSet;

public class CadastrarTurma {
	public void cadastro(Turma t) throws Exception{
		TreeSet<Turma> turmas = new TreeSet<Turma>();
		
		try{
			FileReader     fr = new FileReader("cadastroTurma.txt");
			BufferedReader br = new BufferedReader(fr);
			FileWriter     fw = new FileWriter("cadastroTurma.txt", true);
			BufferedWriter bw = new BufferedWriter(fw);
			
			String linha;
			String[] leitura;
			Turma operacao;
			
			while((linha=br.readLine())!=null){
				leitura=linha.split("\\|",4);
				operacao = new Turma(leitura[0], leitura[1], leitura[2], Integer.parseInt(leitura[3]));
				turmas.add(operacao);
			}
			if(turmas.contains(t)){
				throw new Exception("Cadastro Existente.");
			}
			else{
				String disciplina = t.getDisciplina();
				String codigo = t.getCodigo();
				int vagas = t.getVagas();
				String periodo = t.getPeriodo();
				
				String entrada = disciplina + "|" + codigo + "|" + vagas + "|"+ periodo;
				bw.append(entrada,0,entrada.length());
				bw.newLine();
				bw.flush();
				fw.close();
				bw.close();
				br.close();
				fr.close();
			}
		} catch (FileNotFoundException fnf) {
			try {
				FileWriter fw = new FileWriter("cadastroTurma.txt", true);
				BufferedWriter bw = new BufferedWriter(fw);
				
				String disciplina = t.getDisciplina();
				String codigo = t.getCodigo();
				int vagas = t.getVagas();
				String periodo = t.getPeriodo();
				
				String entrada = disciplina + "|" + codigo + "|" + vagas + "|"+ periodo;
				bw.append(entrada,0,entrada.length());
				bw.newLine();
				bw.flush();
				fw.close();
				bw.close();
			} catch (FileNotFoundException e1) {}
		}
	}
}
